package com.example.crossborderecommerce.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.crossborderecommerce.entity.Admin;
import com.example.crossborderecommerce.entity.LogisticsProvider;
import com.example.crossborderecommerce.entity.ProductCategory;
import com.example.crossborderecommerce.entity.Result;
import com.example.crossborderecommerce.mapper.ProductCategoryMapper;
import com.example.crossborderecommerce.service.IAdminService;
import com.example.crossborderecommerce.service.IProductCategoryService;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 产品分类模块
 *
 * @author Yolanda
 * @since 2024-05-09
 */
@RestController
@Transactional
@RequestMapping("/product-category")
public class ProductCategoryController {
    @Resource
    IProductCategoryService productCategoryService;
    @Resource
    IAdminService adminService;
    @Resource
    ProductCategoryMapper productCategoryMapper;

    /**
     * 添加产品分类
     * @param productCategory
     * @return
     */
    @PostMapping("/save")
    public Result save(@RequestBody ProductCategory productCategory) {
        boolean res = productCategoryService.save(productCategory);
        if(res) {
            return Result.success("添加产品分类成功！");
        }
        return Result.error("添加产品分类失败！");
    }

    /**
     * 修改产品分类
     * @param productCategory
     * @return
     */
    @PostMapping("/update")
    public Result update(@RequestBody ProductCategory productCategory) {
        boolean res = productCategoryService.saveOrUpdate(productCategory);
        if (res) {
            return Result.success("修改产品分类成功！");
        }
        return Result.error("修改产品分类失败！");
    }
    
    /**
     * 删除产品分类
     * @param productCategory
     * @return
     */
    @PostMapping("/delete")
    public Result delete(@RequestBody ProductCategory productCategory) {
        boolean res = productCategoryService.removeById(productCategory);
        if(res) {
            return Result.success("删除产品分类成功！");
        }
        return Result.error("删除产品分类失败！");
    }

    /**
     * 删除一系列产品分类
     * @param ids
     * @return
     */
    @GetMapping("/deleteBatch")
    public Result deleteBatch(@RequestParam String ids) {
        List<String> productCategoryIds = Arrays.stream(ids.split(",")).collect(Collectors.toList());
        boolean res = productCategoryService.removeByIds(productCategoryIds);
        if(res) {
            return Result.success("删除产品分类成功！");
        }
        return Result.error("删除产品分类失败！");
    }

    /**
     * 以列表形式返回所有的产品分类
     * @return
     */
    @GetMapping("/findAll")
    public Result findAll() {
        List<ProductCategory> productCategoryList = productCategoryService.list();
        if(productCategoryList == null) {
            return Result.error("获取全部产品类别失败！");
        }
        for(ProductCategory productCategory : productCategoryList) {
            if(productCategory.getParentCategoryId() != null) {
                ProductCategory productCategory1 = productCategoryService.getById(productCategory.getParentCategoryId());
                productCategory.setParentCategoryName(productCategory1.getName());
            }
        }
        return Result.success("获取全部产品类别成功！", productCategoryList);
    }

    /**
     * 分页查询所有的产品分类
     * @param pageNum
     * @param pageSize
     * @return
     */
    @GetMapping("/findPage")
    public Result findPage(@RequestParam(defaultValue = "") String parentCategoryName,
                           @RequestParam(defaultValue = "") String name,
                           @RequestParam(defaultValue = "-1") String adminId,
                           @RequestParam Integer pageNum,
                           @RequestParam Integer pageSize) {
        Page<ProductCategory> productCategoryPage = new Page<>(pageNum, pageSize);
        List<ProductCategory> productCategoryList = productCategoryMapper.getProductCategoryByPage(productCategoryPage, adminId, parentCategoryName, name);
        for(ProductCategory productCategory : productCategoryList) {
            Admin admin = adminService.getById(productCategory.getAdminId());
            productCategory.setAdminName(admin.getName());
            if(productCategory.getParentCategoryId() != null) {
                ProductCategory productCategory1 = productCategoryService.getById(productCategory.getParentCategoryId());
                StringBuilder categoryName = new StringBuilder(productCategory1.getName());
                while(productCategory1.getParentCategoryId() != null) {
                    productCategory1 = productCategoryService.getById(productCategory1.getParentCategoryId());
                    categoryName.insert(0, productCategory1.getName() + "/");
                }
                productCategory.setParentCategoryName(categoryName.toString());
            }
        }
        Page<ProductCategory> newProductCategoryPage = new Page<>(pageNum, pageSize);
        newProductCategoryPage.setRecords(productCategoryList);
        newProductCategoryPage.setTotal(productCategoryPage.getTotal());
        return Result.success("成功查询所有产品分类！",newProductCategoryPage);
    }

    /**
     * 查询产品类别中所有创建人
     * @return
     */
    @GetMapping("/findAdminsInProductCategory")
    public Result findAdminsInProductCategory() {
        List<Admin> adminList = productCategoryService.findAdminsInProductCategory();
        if(adminList == null) {
            return Result.error("获取管理员信息失败！");
        }
        return Result.success(adminList);
    }

    /**
     * 导出产品信息
     * @param adminId
     * @param response
     * @return
     */
    @GetMapping("exportProductCategoryList")
    public Result exportProductCategoryList(@RequestParam(defaultValue = "") String parentCategoryName,
                                            @RequestParam(defaultValue = "") String name,
                                            @RequestParam(defaultValue = "-1") String adminId,
                                            HttpServletResponse response) {
        List<ProductCategory> productCategoryList = productCategoryMapper.getProductCategory(adminId, parentCategoryName, name);
        for(ProductCategory productCategory : productCategoryList) {
            Admin admin = adminService.getById(productCategory.getAdminId());
            productCategory.setAdminName(admin.getName());
            if(productCategory.getParentCategoryId() != null) {
                ProductCategory productCategory1 = productCategoryService.getById(productCategory.getParentCategoryId());
                StringBuilder categoryName = new StringBuilder(productCategory1.getName());
                while(productCategory1.getParentCategoryId() != null) {
                    productCategory1 = productCategoryService.getById(productCategory1.getParentCategoryId());
                    categoryName.insert(0, productCategory1.getName() + "/");
                }
                productCategory.setParentCategoryName(categoryName.toString());
            }
        }
        HSSFWorkbook wb = new HSSFWorkbook(); // 导出到excel文件中
        HSSFSheet sheet = wb.createSheet("表一");
        HSSFRow row = sheet.createRow(0);
        HSSFCellStyle style = wb.createCellStyle();
        style.setAlignment(HorizontalAlignment.CENTER);
        HSSFCell cell = row.createCell((short) 0);
        cell.setCellValue("ID");
        cell.setCellStyle(style);
        cell = row.createCell((short) 1);
        cell.setCellValue("上级分类");
        cell.setCellStyle(style);
        cell = row.createCell((short) 2);
        cell.setCellValue("分类名称");
        cell.setCellStyle(style);
        cell = row.createCell((short) 3);
        cell.setCellValue("创建人");
        cell.setCellStyle(style);
        cell = row.createCell((short) 4);
        cell.setCellValue("创建时间");
        cell.setCellStyle(style);
        SimpleDateFormat inputDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
        SimpleDateFormat outputDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        for (int i = 0; i < productCategoryList.size(); i++) {
            row = sheet.createRow(i + 1);
            ProductCategory productCategory = productCategoryList.get(i);
            row.createCell((short) 0).setCellValue(productCategory.getId());
            if(productCategory.getParentCategoryId() != null) {
                row.createCell((short) 1).setCellValue(productCategory.getParentCategoryName());
            }
            else {
                row.createCell((short) 1).setCellValue("无");
            }
            row.createCell((short) 2).setCellValue(productCategory.getName());
            row.createCell((short) 3).setCellValue(productCategory.getAdminName());
            try {
                Date createTime = inputDateFormat.parse(productCategory.getCreateTime().toString()); // 假设 getCreateTime 返回的是 String
                row.createCell((short) 4).setCellValue(outputDateFormat.format(createTime));
            } catch (ParseException e) {
                row.createCell((short) 4).setCellValue(productCategory.getCreateTime().toString());
            }
        }
        String fileName = "exportProductCategoryList.xls";
        // 用户下载
        try {
            ServletOutputStream outputStream = null;
            response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
            response.setHeader("Content-Disposition", "attachment;filename="+ URLEncoder.encode(fileName, "UTF-8"));
            outputStream = response.getOutputStream();
            wb.write(outputStream);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return Result.success("exportProductCategoryList");
    }
}
